package com.huobi.pro.mirror;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.stream.IntStream;

import org.springframework.stereotype.Service;

import lombok.Data;

/**
 * 交易内存镜像
 * 
 * @author jiangwei
 *
 */
@Service
public class TradeMirrorService {

	Span[] spans = new Span[] { new Span() };
	class Span {
		private Mirror[] data = new Mirror[50];

		Span() {
			for (int i = 0; i < data.length; i++) {
				data[i] = new Mirror(0);
			}
		}

		public String toString() {
			StringBuilder buf = new StringBuilder();
			for(Mirror d:data) {
				buf.append("\t");
				buf.append(d.toString()).append("\r\n");
			}
			return buf.toString();
		}
		
		public void push(Date tradeDate, BigDecimal high, BigDecimal low) {
			long minute = tradeDate.getTime()/1000;
			Mirror mirror = findMirror(minute);
			mirror.data(high,low);
		}
		
		public Mirror findMirror(long minute) {
			// 获取区间
			for (Mirror m : data) {
				if (m.between(minute)) {
					return m;
				}
			}
			// 没有找到想要的区间
			int size = data.length - 1;
			for (int i = size; size > 1; i--) {
				if (i == 0)
					break;
				data[i] = data[i - 1];
				data[i].id = i;
			}
			// 创建新的区间
			data[0] = new Mirror(minute);

			return data[0];
		}
	}

	@Data static class Mirror {
		private long startTime, endTime;
		private int id = 0;
		private BigDecimal high = BigDecimal.ZERO;
		private BigDecimal low = BigDecimal.ZERO;
		public Mirror(long startTime) {
			this.startTime = startTime;
			this.endTime = startTime + (1 * 60);
		}

		public void data(BigDecimal high, BigDecimal low) {
			if (this.high.compareTo(BigDecimal.ZERO) == 0)
				this.high = high;
			if (this.low.compareTo(BigDecimal.ZERO) == 0)
				this.low = low;
			
			if(this.high.compareTo(high)<0)
				this.high = high;
			if(this.low.compareTo(low)>0)
				this.low = low;
		}
		
		public boolean between(long minute) {
			return minute >= startTime && minute < endTime;
		}
		
		public String toString() {
			StringBuilder buf = new StringBuilder();
			buf.append(id + ":" + toDate(startTime) + "/" + toDate(endTime) + "/" + high + ":" + low);
			return buf.toString();
		}
		private String toDate(long time) {
			LocalDateTime date = LocalDateTime.ofInstant(Instant.ofEpochSecond(time), ZoneId.systemDefault());
			return date.getYear()+"-"+date.getMonth().getValue()+"-"+date.getDayOfMonth()+" "+date.getHour()+":"+date.getMinute();
		}
	}

	public void push(Date tradeDate, BigDecimal high, BigDecimal low) {
		IntStream.range(0, spans.length).forEach(i -> {
			spans[i].push(tradeDate, high, low);
		});
		for(Span span:spans) {
			System.out.println(span.toString());
		}
	}

	public boolean trade() {
		return false;
	}
	
}
